import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { CreatePageDto } from './dto/create-page.dto';
import { Page } from './page.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Raw, In } from 'typeorm';
import { RemovePageDto } from './dto/remove-page.dto';

@Injectable()
export class PageService {
  constructor(
    @InjectRepository(Page)
    private pageRepository: Repository<Page>,
  ) {}

  // 增加
  async create(createPageDto: CreatePageDto): Promise<any> {
    const { createdAt } = createPageDto;
    createPageDto.createdAt = createdAt || new Date();
    createPageDto.updatedAt = new Date();

    delete createPageDto.id;

    return await this.pageRepository.save(createPageDto);
  }
    // 复制
    async copy(createPageDto: CreatePageDto): Promise<any> {
      const { createdAt } = createPageDto;
      createPageDto.createdAt = createdAt || new Date();
      createPageDto.updatedAt = new Date();
  
      //delete createPageDto.id;
    var res=await this.pageRepository
      .createQueryBuilder('page')
      .where([{ id:createPageDto.id }])
      .getOne();
     delete res.id;
     res.createdAt = createdAt || new Date();
     res.updatedAt = new Date();
      return await this.pageRepository.save(res);
    }

  // 删除
  async delete(removePageDto: RemovePageDto): Promise<any> {
    const { ids } = removePageDto;

    return this.pageRepository.delete(ids);
  }

  // 更新
  async update(updatePageData): Promise<any> {
    const { id, updatePageDto } = updatePageData;
    updatePageDto.updatedAt = new Date();

    return await this.pageRepository.update(id, updatePageDto);
  }

  // 列表
  async findAll(query: any): Promise<any> {
    const { keyword, category, status, page = 1, limit = 10 } = query;
    const skip = (page - 1) * limit;

    let params = {
      skip,
      take: limit,
    };

    let whereParams = {};

    if (keyword) {
      whereParams = Object.assign(whereParams, {
        name: Like(`%${keyword}%`),
      });
    }

    if (category) {
      whereParams = Object.assign(whereParams, {
        category: In(category),
      });
    }

    if (status) {
      whereParams = Object.assign(whereParams, {
        status: status === 'true' ? true : false,
      });
    }

    params = Object.assign(
      params,
      {
        where: whereParams,
      },
      {
        order: {
          updatedAt: 'DESC',
        },
      },
    );

    const [data, total] = await this.pageRepository.findAndCount(params);

    return {
      total,
      data,
    };
  }

  // 根据ID查找
  async findOneById(params: any): Promise<any> {
    const { id } = params;

    return this.pageRepository
      .createQueryBuilder('page')
      .where([{ id }])
      .getOne();
  }

  // 数量
  async getCount() {
    return await this.pageRepository.count();
  }
}
